<?php

$totalCount = 0;
class importPlayerTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
     $this->addArguments(array(
       new sfCommandArgument('file', sfCommandArgument::REQUIRED, 'My argument'),
       new sfCommandArgument('totalCount', sfCommandArgument::REQUIRED, 'My argument'),
     ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
      // add your own options here
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'importPlayer';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [import|INFO] task does things.
Call it with:

  [php symfony import|INFO]
EOF;
  }

  public function doLogSection($section, $message, $size = NULL, $style ='INFO')
  {
      global $totalCount;

      $q = Doctrine::getTable("DataImportStatus")
          ->createQuery()
          ->orderBy("date desc")
          ->limit(1);
      $r = $q->execute();

      $is = new DataImportStatus();
      $is->setDate(gmdate("Y-m-d H:i:s", time()));
      $is->setStatus($section);
      $is->setText($message);
      $is->setStatustotal($totalCount);
      if (isset($size))
      {
          $is->setStatusbar(0);
          $size = null;
      }
      elseif ($r->count() == 1)
      {
          $is->setStatusbar($r->getFirst()->getStatusbar()+1);
      }
      else
      {
          $is->setStatusbar(0);
      }
      $is->save();
      $this->logsection($section, $message, $size, $style);
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // add your code here
    //

    global $totalCount;
    $totalCount = $arguments['totalCount'];
    $log=1;
    $data = unserialize(file_get_contents("data/import/".$arguments['file']));
    $this->doLogSection("Working", "Reason: ".utf8_decode($data['player']));


    $query = Doctrine::getTable("Raid")
        ->createQuery()
        ->where("short=?", $data['raid'])
        ->andWhere("server=?", $data['realm']);
    $result = $query->execute();
    $r = null;
    if ($result->count() > 0)
        $r = $result->getFirst();
    else
    {
        $r = new Raid();
        $r->setName($data['raid']);
        $r->setShort($data['raid']);
        $r->setVisible(0);
        $r->setServer($data['realm']);
    }

    $query = Doctrine::getTable("TType")
        ->createQuery()
        ->where("ttype=?", "P");
    $type_p = $result->getFirst();

    $actiont = $r->getVersion();

    $player = utf8_decode($data['player']);
    foreach ( $data['data']["recentactions"] as $actiontime => $ev)
    {
        $history = new History();
        $history->fromArray($ev);

        if ($actiontime > $actiont)
            $actiont = $actiontime;

        $waitlist = 0;
        if ($ev["waitlist"] == 1)
            $waitlist = 1;
        $history->setWaitlistflag($waitlist);
        $history->setZoneid(0);

        //echo "- dates - ";
        $history->setSavedate(($actiontime));
        if (!isset($ev["actiontime"]))
            $ev["actiontime"] = $ev["datetime"];
        $history->setActiondate(($ev["actiontime"]));
        $history->setDate(($ev["datetime"]));
        //$history->setOfficer($officer);
        $history->setRaid($r);

        //echo "ttype - ";
        //print_r($ev);
        $query = Doctrine::getTable("TType")
            ->createQuery()
            ->where("ttype=?", $ev["ty"]);
        $result = $query->execute();
        //echo $result->count();
        if ($result->count() > 0)
            $history->setTType($result->getFirst());
        else
             $history->setTtype($type_p);

        unset($query, $result);

        //echo "aaction - ";
        $query = Doctrine::getTable("Aaction")
            ->createQuery()
            ->where("name=?", $ev["action"]);
        $result = $query->execute();
        if ($result->count() > 0)
            $history->setAaction($result->getFirst());
        else
            $history->setAaction("I");
        unset($query, $result);

        //echo "reason - ";
        $query = Doctrine::getTable("Reason")
            ->createQuery()
            ->where("name=?", $ev["reason"]);
        $result = $query->execute();
        if ($result->count() > 0)
            $history->setReason($result->getFirst());
        else
        {
            $reason = new Reason();
            $reason->setName($ev["reason"]);
            $reason->save();
            $history->setReason($reason);
        }
        unset($query, $result);

        //echo "player - ";
        $query = Doctrine::getTable("Player")
                        ->createQuery()
                        ->where("name=?", utf8_encode($player));
        $result = $query->execute();
        if ($result->count() > 0)
            $history->setPlayer($result->getFirst());
        unset($query, $result);

        try
        {
            $history->trySave();
            $this->doLogSection("Working", "New Record: ".$history->getPlayer()->getFullname()." - ".$history->getDate()." ".$history->getValue());
        }
        catch (exception $ex)
        {
            $this->doLogSection("Working", "Old Record: ".$history->getPlayer()->getFullname()." - ".$history->getDate()." ".$history->getValue());
        }
        unset($history);
    }
    $r->setVersion($actiont);
    $r->save();

    unlink("data/import/".$arguments['file']);

    /*
    $r = Doctrine::getTable("History")->getLastLog('2009-07-05 17:01:59', 10, 1);
    $r = $r->getFirst();

    $r = Doctrine::getTable("PlayerHistory")->updatePoints(2, 1);

    $newHistory = new History();
    $newHistory->setDate('2009-07-05 17:01:59');
    $newHistory->setActiondate('2009-07-05 17:02:51');
    $newHistory->setSavedate($newHistory->getActiondate());
    $newHistory->setLogdate(time());
    $newHistory->setLogcomment(' ');
    $newHistory->setComment(' ');
    $newHistory->setItemid(0);
    $newHistory->setOfficerid(0);
    $newHistory->setPlayerid(10);
    $newHistory->setRaidid(1);
    $newHistory->setReasonid(831);
    $newHistory->setTtype('I');
    $newHistory->setValue('0');
    $newHistory->setWaitlistflag(0);
    $newHistory->setZoneid(0);
    $newHistory->setAaction("D");
    $newHistory->save();

    $this->logsection("do-nothing", "I did nothing...");
    //print_r($r->getAction());
    */


  }
}
